﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

using Gift.DAL;
using Gift.Model;
using System.Data;
using System.Text;
using System.Xml;
using Gift.WebApp;


namespace WebApp.admin.goods
{
    public partial class exchangeGoods : BaseAdmin
    {

        protected string kw = "";
        protected string order = "id";
        protected int ot = 1;
        protected int pageCount = 0;
        protected int pageIndex = 1;
        protected int pageSize = 20;
        protected PageList pl = new PageList();

        protected int t = 0;
        protected int total = 0;

        string _addDisplay = "none";

        public string AddDisplay
        {
            get { return _addDisplay; }
        }
        bool _isEdit = false;
        bool _isDeleted = false;

        // Methods
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            DataTable goodGalleryByGoods;
            string pathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
            string str2 = base.Request.Form["Item"];
            if (str2.Contains(","))
            {
                Array array = str2.Split(new char[] { ',' });
                foreach (string str3 in array)
                {
                    goodGalleryByGoods = BaseFactory.theGoodGallery.GetGoodGalleryByGoods(Convert.ToInt32(str3));
                    if (BaseFactory.theGoods.Delete(Convert.ToInt32(str3)))
                    {
                        foreach (DataRow row in goodGalleryByGoods.Rows)
                        {
                            if ((row["thumbImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["thumbImg"].ToString())))
                            {
                                File.Delete(base.Server.MapPath(row["thumbImg"].ToString()));
                            }
                            if ((row["smallImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["smallImg"].ToString())))
                            {
                                File.Delete(base.Server.MapPath(row["smallImg"].ToString()));
                            }
                            if ((row["bigImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["bigImg"].ToString())))
                            {
                                File.Delete(base.Server.MapPath(row["bigImg"].ToString()));
                            }
                        }
                    }
                }
            }
            else
            {
                goodGalleryByGoods = BaseFactory.theGoodGallery.GetGoodGalleryByGoods(Convert.ToInt32(str2));
                if (BaseFactory.theGoods.Delete(Convert.ToInt32(str2)))
                {
                    foreach (DataRow row in goodGalleryByGoods.Rows)
                    {
                        if ((row["thumbImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["thumbImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["thumbImg"].ToString()));
                        }
                        if ((row["smallImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["smallImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["smallImg"].ToString()));
                        }
                        if ((row["bigImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["bigImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["bigImg"].ToString()));
                        }
                    }
                }
            }
            base.Response.Redirect(pathAndQuery);
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                string term = "";
                if ((base.Request.QueryString["t"] != null) && (base.Request.QueryString["kw"] != null))
                {
                    this.kw = base.Request.QueryString["kw"];
                    if (base.Request.QueryString["t"] != "categoryName")
                    {
                        term = base.Request.QueryString["t"] + " like '%" + this.kw + "%'";
                    }
                    else
                    {
                        term = "tbGoods.id in(select goods from tb_goodsCategory a left join tb_category b on a.category=b.categoryIdentity where b.categoryName like '%" + this.kw + "%')";
                    }
                }
             
                ExcelHelper.ExportDataTableToExcel(BaseFactory.theGoods.GetAllGoodsByTerm(term), DateTime.Now.ToString("yyyyMMddHHmmssffffff") + ".xls", "商品列表");
            }
            catch
            {
            }
        }

      

        protected string GetCategoryName(object category)
        {
            string str = "";
            try
            {
                ArrayList list = ArrayList.Adapter(category.ToString().Split(new char[] { ',' }));
                for (int i = 0; i < list.Count; i++)
                {
                    DataTable categoryByCategoryIdentity = BaseFactory.theCategory.GetCategoryByCategoryIdentity(Convert.ToInt32(list[i]));
                    str = str + ((i == 0) ? categoryByCategoryIdentity.Rows[0]["categoryName"].ToString() : ("," + categoryByCategoryIdentity.Rows[0]["categoryName"].ToString()));
                }
            }
            catch
            {
            }
            return str;
        }

        private void GoodsBind()
        {
            try
            {
                if (base.Request.QueryString["p"] != null)
                {
                    this.pageIndex = int.Parse(base.Request.QueryString["p"]);
                }
                if (base.Request.QueryString["ps"] != null)
                {
                    this.pageSize = Convert.ToInt32(base.Request.QueryString["ps"]);
                }
                if (base.Request.QueryString["or"] != null)
                {
                    this.order = base.Request.QueryString["or"];
                }
                if (base.Request.QueryString["ot"] != null)
                {
                    this.ot = Convert.ToInt32(base.Request.QueryString["ot"]);
                }
                this.pl.TblName = "view_goods";
                this.pl.StrGetFields = "id,goodsName,goodsNo,category,salePrice,isShelves,isBest,isNew,isTopSelling,inventory,isFromFreight,isnull(isProfShelves,0) as isProfShelves ";
                this.pl.FldName = this.order;
                this.pl.PageSize = this.pageSize;
                this.pl.PageIndex = this.pageIndex;
                this.pl.DoCount = 1;
                this.pl.OrderType = this.ot;
                if ((base.Request.QueryString["t"] != null) && (base.Request.QueryString["kw"] != null))
                {
                    this.kw = base.Request.QueryString["kw"];
                    if (base.Request.QueryString["t"] != "categoryName")
                    {
                        this.pl.StrWhere = base.Request.QueryString["t"] + " like '%" + this.kw + "%' ";
                    }
                    else
                    {
                        this.pl.StrWhere = "id in(select goods from tb_goodsCategory a left join tb_category b on a.category=b.categoryIdentity where b.categoryName like '%" + this.kw + "%') ";
                    }
                }
        
               // tbAdminlogin admin = this.Session["admin_user"] as tbAdminlogin;
                //DataTable adminGroupById = this.agm.GetAdminGroupById(admin.GroupId);
                //if ((adminGroupById.Rows.Count > 0) && (Convert.ToInt32(adminGroupById.Rows[0]["isSupplier"]) == 1))
                //{
                this.pl.StrWhere = this.pl.StrWhere + " and creator=" + base.Administrator.AdminUserId;
               // }
                this.total = Convert.ToInt32(BaseFactory.thePageList.GetPageList(this.pl).Rows[0]["Total"]);
                this.pl.DoCount = 0;
                DataTable pageList = BaseFactory.thePageList.GetPageList(this.pl);
                new PageListNo().DelPageSize(pageList, this.total);

                this.rptGoods.DataSource = pageList.DefaultView;
                this.rptGoods.DataBind();
            }
            catch
            {
            }
        }

        protected override object LoadPageStateFromPersistenceMedium()
        {
            byte[] inArray = ViewStateCompression.DeCompress(Convert.FromBase64String(base.Request.Form.Get("__MSPVSTATE")));
            LosFormatter formatter = new LosFormatter();
            return formatter.Deserialize(Convert.ToBase64String(inArray));
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.ValidateLoginUser();
            this.DeletedGoods();
            if (!base.IsPostBack)
            {
                if (base.Request.QueryString["t"] != null)
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "sGs", "<script type=\"text/javascript\">selectIsExitItem(\"selectGoods\",\"" + base.Request.QueryString["t"] + "\");</script>");
                }
                if (base.Request.QueryString["ps"] != null)
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "sPs", "<script type=\"text/javascript\">selectIsExitItem(\"selectPageSize\",\"" + base.Request.QueryString["ps"] + "\");</script>");
                }
          
                this.GoodsBind();
            }
        }

        void ValidateLoginUser()
        {
            if(!base.GetValidateLoginRule(Gift.Model.ENUM.ERule.GoodsList))
            {
                base.Response.Write("<script language=javascript>window.top.location.href='../login.aspx';</script>");
                base.Response.End();
            }
            if(base.GetValidateLoginRule(Gift.Model.ENUM.ERule.GoodsAdd))
            {
                _addDisplay = "block";
            }
            if(base.GetValidateLoginRule(Gift.Model.ENUM.ERule.GoodsEdit))
            {
                _isEdit = true;
            }
            if(base.GetValidateLoginRule(Gift.Model.ENUM.ERule.GoodsDeleted))
            {
                _isDeleted = true;
            }
        }

        void DeletedGoods()
        {

            string pathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
            int goods = 0;
            if (Request.QueryString["action"] == "del")
            {
                goods = Convert.ToInt32(Request.QueryString["id"]);
                DataTable goodGalleryByGoods = BaseFactory.theGoodGallery.GetGoodGalleryByGoods(goods);
                if (BaseFactory.theGoods.Delete(goods))
                {
                    foreach (DataRow row in goodGalleryByGoods.Rows)
                    {
                        if ((row["thumbImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["thumbImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["thumbImg"].ToString()));
                        }
                        if ((row["smallImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["smallImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["smallImg"].ToString()));
                        }
                        if ((row["bigImg"].ToString() != "") && File.Exists(base.Server.MapPath(row["bigImg"].ToString())))
                        {
                            File.Delete(base.Server.MapPath(row["bigImg"].ToString()));
                        }
                    }
                    base.Response.Redirect(pathAndQuery.Replace("action=","noaction="));
                }
                else
                {
                    base.ClientScript.RegisterStartupScript(base.GetType(), "sd", "<script language=\"javascript\" defer>alert('删除失败！');</script>");
                }
            }
        }


        protected override void SavePageStateToPersistenceMedium(object pViewState)
        {
            LosFormatter formatter = new LosFormatter();
            StringWriter output = new StringWriter();
            formatter.Serialize(output, pViewState);
            string hiddenFieldInitialValue = Convert.ToBase64String(ViewStateCompression.Compress(Convert.FromBase64String(output.ToString())));
            base.ClientScript.RegisterHiddenField("__MSPVSTATE", hiddenFieldInitialValue);
        }

        protected void rptGoods_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if(!_isEdit)
                {
                  e.Item.FindControl("divEdit").Visible = false;
                }
                if (!_isDeleted)
                {
                    e.Item.FindControl("divDeleted").Visible = false;
                }
            }
        }

    }
}
